import './index.less'
import {CCard} from '@/components/card'
import {IconImg} from '@/components/image'
import PmBaseInfo from '@/components/others/pm/pmBaseInfo'
import {CnMediumSpan, CnNormalSpan} from '@/components/text'
import useCollapse from '@/hooks/collapse'
import {useRouteQuery} from '@/hooks/pageRedirect'
import useBackLogs from '@/hooks/pm/backLogs'
import useProgress from '@/hooks/pm/progress'
import useTabs from '@/hooks/tabsHook'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {toScoreBySelf, toSetTarget, toTargetBaseInfo} from '@/libs/pageRedirect'
import {message} from 'ant-design-vue'
import {defineComponent, computed, onMounted, nextTick} from 'vue'
import {useLinkPmStore} from '@/pinia'
import {
  selectWorkTaskCountApi,
  selectHanderWorkByPageApi,
  selectNotHanderWorkByPageApi
} from '@/api/workTask'
export default defineComponent({
  name: 'myPerformance',
  setup(props, ctx) {
    const {store} = useGlobalAPI()

    const loginUserInfo = computed(() => store.getters['dingding/ddUserInfo'])

    const {getQueryData} = useRouteQuery({queryKeys: ['pmId']})
    const pageQuery = getQueryData<{pmId: string}>()

    const {updateBackLogs, notHanderWorkList, updateHanderWorkList, handerWorkList} = useBackLogs()

    const {tabsKey, changeTabsKey} = useTabs<number>({
      defaultKey: 0
    })

    const {getProgressById, progressById} = useProgress()

    const {closeCollapse, collapseVisible, openCollapse} = useCollapse({defaultVisible: false})

    const {
      closeCollapse: closeCollapse1,
      collapseVisible: collapseVisible1,
      openCollapse: openCollapse1
    } = useCollapse({defaultVisible: false})

    const currentLinkPmId = ref(null)

    const linkPmStore = useLinkPmStore()

    // 待办任务和已办任务数量
    const taskCount = ref({
      waitWorkTaskCount: 0,
      completeWorkTaskCount: 0
    })

    // 待办任务容器Ref
    const notHanderTaskContainerRef = ref(null)

    // 已办任务容器Ref
    const handerTaskContainerRef = ref(null)

    // 待办任务容器加载标识
    const isNotHanderTaskContainerLoading = ref(false)

    // 已办任务容器加载标识
    const isHanderTaskContainerLoading = ref(false)

    // 待办分页参数
    const notHanderWorkPageParam = ref({
      page: 1,
      size: 20
    })

    // 已办分页参数
    const handerWorkPageParam = ref({
      page: 1,
      size: 20
    })

    // 待办任务列表
    const nNotHanderWorkList = ref([])

    // 已办任务列表
    const nHanderWorkList = ref([])

    // 查询待办任务和已办任务数量
    const selectWorkTaskCountFunc = async () => {
      await selectWorkTaskCountApi({
        userDDId: loginUserInfo.value.userId
      }).then(res => {
        console.log('#任务数量', res)
        taskCount.value = res.data
      })
    }

    // 查询待办任务列表
    const selectNotHanderWorkByPageFunc = async () => {
      isNotHanderTaskContainerLoading.value = true
      let data = {
        page: notHanderWorkPageParam.value.page,
        size: notHanderWorkPageParam.value.size,
        userDDId: loginUserInfo.value.userId
      }
      await selectNotHanderWorkByPageApi(data)
        .then(res => {
          if (data.page == 1) {
            nNotHanderWorkList.value = res.data
            console.table(nNotHanderWorkList.value)
          } else {
            nNotHanderWorkList.value = nNotHanderWorkList.value.concat(res.data)
          }
        })
        .finally(() => {
          isNotHanderTaskContainerLoading.value = false
        })
    }

    // 查询已办任务列表
    const selectHanderWorkByPageFunc = async () => {
      isHanderTaskContainerLoading.value = true
      let data = {
        page: handerWorkPageParam.value.page,
        size: handerWorkPageParam.value.size,
        userDDId: loginUserInfo.value.userId
      }
      await selectHanderWorkByPageApi(data)
        .then(res => {
          if (data.page == 1) {
            nHanderWorkList.value = res.data
            console.table(nHanderWorkList.value)
          } else {
            nHanderWorkList.value = nHanderWorkList.value.concat(res.data)
          }
        })
        .finally(() => {
          isHanderTaskContainerLoading.value = false
        })
    }

    // 待办任务容器滚动到底处理
    const notHanderTaskContainerIsScrollBottomDispose = () => {
      console.log('#待办任务总数', taskCount.value.waitWorkTaskCount)
      console.log('#待办任务当前数量', nNotHanderWorkList.value.length)

      // 判断是否全部加载完成
      if (nNotHanderWorkList.value.length != taskCount.value.waitWorkTaskCount) {
        notHanderWorkPageParam.value.page += 1
        console.log('#待办滚动触发请求')
        selectNotHanderWorkByPageFunc()
      }
    }

    // 已办任务容器滚动到底处理
    const handerTaskContainerIsScrollBottomDispose = () => {
      console.log('#已办任务总数', taskCount.value.completeWorkTaskCount)
      console.log('#已办任务当前数量', nHanderWorkList.value.length)

      // 判断是否全部加载完成
      if (nHanderWorkList.value.length != taskCount.value.completeWorkTaskCount) {
        handerWorkPageParam.value.page += 1
        console.log('#已办滚动触发请求')
        selectHanderWorkByPageFunc()
      }
    }

    onMounted(() => {
      updateBackLogs()
      updateHanderWorkList()
      selectWorkTaskCountFunc()
      selectNotHanderWorkByPageFunc()
      selectHanderWorkByPageFunc()
      // alert(location.href)
      // message.success(location.href)
      // message.success(search)
    })

    nextTick(() => {})

    const notHanderTaskContainerScroll = () => {
      console.log('待办滚动')

      if (notHanderTaskContainerRef.value) {
        const {scrollTop, scrollHeight, clientHeight} = notHanderTaskContainerRef.value
        if (scrollTop + clientHeight >= scrollHeight) {
          // 滚动到底部
          console.log('待办已滚动到最底部')
          notHanderTaskContainerIsScrollBottomDispose()
        }
      }
    }

    const handerTaskContainerScroll = () => {
      console.log('已办滚动')

      if (handerTaskContainerRef.value) {
        const {scrollTop, scrollHeight, clientHeight} = handerTaskContainerRef.value
        if (scrollTop + clientHeight >= scrollHeight) {
          // 滚动到底部
          console.log('已办已滚动到最底部')
          handerTaskContainerIsScrollBottomDispose()
        }
      }
    }

    const notHanderWorkClick = async item => {
      let progress = await getProgressById({pmProgressId: item.pmProgressId})
      console.log(progress, 'ttcb')
      if (!progress) return
      switch (progress.pmProgressStep) {
        case 1:
          toSetTarget({
            pmId: item.pmId,
            progressId: item.pmProgressId
          })
          break
        case 2:
          toTargetBaseInfo({
            defaultPmId: item.pmId,
            title: item.workTaskContent.replace(/\S{2}:([^需要您的确认]{0,})需要您的确认$/, '$1'),
            type: 'targetByLeader'
          })
          break
        case 4:
          toScoreBySelf({
            defaultPmId: item.pmId
          })
          break
        case 6:
        case 7:
          toTargetBaseInfo({
            defaultPmId: item.pmId,
            title: item.workTaskContent.replace(/\S{2}:([^需要您的评分]{0,})需要您的评分$/, '$1'),
            type: 'scoreByLeader'
          })
          break
      }
    }

    return () => (
      <div>
        <CCard class='mb-16 CBC-bg-toRight' title='' showTitle={false}>
          <a-tabs
            class='rounded-4'
            v-model={[tabsKey.value, 'activeKey']}
            onTabClick={(data: number) => {
              if (data === tabsKey.value) {
                switch (data) {
                  case 0:
                    collapseVisible.value ? closeCollapse() : openCollapse()
                    break
                  case 1:
                    collapseVisible1.value ? closeCollapse1() : openCollapse1()
                    break
                }
              }
            }}
          >
            <a-tab-pane
              class='relative'
              key={0}
              // tab={`待办事项(${notHanderWorkList.value.length})`}
              tab={`待办事项(${taskCount.value.waitWorkTaskCount})`}
            >
              {nNotHanderWorkList.value.length
                ? [
                    <div
                      class={[
                        'flex flex-col items-center gap-y-4 mt-16 transition-all overflow-y-auto',
                        collapseVisible.value
                          ? 'h-200 p-8 pb-28 not_hander_work_container_box'
                          : 'h-0 '
                      ]}
                      ref={notHanderTaskContainerRef}
                      onScroll={notHanderTaskContainerScroll}
                    >
                      {nNotHanderWorkList.value.map(item => (
                        <div
                          class='w-full flex items-center justify-between cursor-pointer rounded-4 p-8 hover:bg-primaryLight'
                          onClick={() => {
                            notHanderWorkClick(item)
                          }}
                        >
                          <span style='letter-spacing: 1px;'>
                            <IconImg
                              imgName='notHander'
                              class='inline-block w-30 h-30 mr-12'
                            ></IconImg>
                            {item.workTaskContent}
                          </span>
                          {/* <CnNormalSpan>{item.createTime}</CnNormalSpan> */}
                          <span>{item.createTime}</span>
                        </div>
                      ))}
                      {/* 加载容器 */}
                      {isNotHanderTaskContainerLoading.value ? (
                        <div class='loading_c_box'>
                          <a-spin size='small' />
                          <span class='text'>加载中...</span>
                        </div>
                      ) : null}

                      {/* 全部加载完成提示 */}
                      {nNotHanderWorkList.value.length == taskCount.value.waitWorkTaskCount ? (
                        <span class='all_loading_ok_tip'>全部加载完成</span>
                      ) : null}
                    </div>,
                    <div class='absolute bottom-0 left-0 w-full transform flex items-center justify-center'>
                      {collapseVisible.value ? (
                        <i
                          class='iconfont icon-shangjiantou-triangle text-14 text-info cursor-pointer'
                          onClick={() => {
                            closeCollapse()
                          }}
                        ></i>
                      ) : (
                        <i
                          class='iconfont icon-xiajiantou-triangle text-14 text-info cursor-pointer'
                          onClick={() => {
                            openCollapse()
                          }}
                        ></i>
                      )}
                    </div>
                  ]
                : null}
            </a-tab-pane>
            <a-tab-pane
              class='relative'
              key={1}
              // tab={`已办事项(${handerWorkList.value.length})`}

              tab={`已办事项(${taskCount.value.completeWorkTaskCount})`}
            >
              {nHanderWorkList.value.length
                ? [
                    <div
                      class={[
                        ' flex flex-col items-center gap-y-4 mt-16 transition-all overflow-y-auto',
                        collapseVisible1.value ? 'h-200 p-8 pb-28 hander_work_container_box' : 'h-0'
                      ]}
                      ref={handerTaskContainerRef}
                      onScroll={handerTaskContainerScroll}
                    >
                      {nHanderWorkList.value.map(item => (
                        <div
                          class='w-full  flex items-center justify-between cursor-pointer rounded-4 p-8 hover:bg-primaryLight'
                          onClick={async () => {
                            let progress = await getProgressById({pmProgressId: item.pmProgressId})
                            console.log(progress)
                            if (!progress) return
                            toTargetBaseInfo({
                              defaultPmId: item.pmId,
                              title: '员工绩效详情',
                              type: 'checkInfo'
                            })
                          }}
                        >
                          <span style='letter-spacing: 1px;'>
                            <IconImg
                              imgName='notHander'
                              class='inline-block w-30 h-30 mr-12'
                            ></IconImg>
                            {item.workTaskContent}
                          </span>
                          {/* <CnNormalSpan>{item.createTime}</CnNormalSpan> */}
                          <span>{item.createTime}</span>
                        </div>
                      ))}
                      {/* 加载容器 */}
                      {isHanderTaskContainerLoading.value ? (
                        <div class='loading_c_box'>
                          <a-spin size='small' />
                          <span class='text'>加载中...</span>
                        </div>
                      ) : null}

                      {/* 全部加载完成提示 */}
                      {nHanderWorkList.value.length == taskCount.value.completeWorkTaskCount ? (
                        <span class='all_loading_ok_tip'>全部加载完成</span>
                      ) : null}
                    </div>,
                    <div class='absolute bottom-0 left-0 w-full transform flex items-center justify-center'>
                      {collapseVisible1.value ? (
                        <i
                          class='iconfont icon-shangjiantou-triangle text-14 text-info cursor-pointer'
                          onClick={() => {
                            closeCollapse1()
                          }}
                        ></i>
                      ) : (
                        <i
                          class='iconfont icon-xiajiantou-triangle text-14 text-info cursor-pointer'
                          onClick={() => {
                            openCollapse1()
                          }}
                        ></i>
                      )}
                    </div>
                  ]
                : null}
            </a-tab-pane>
          </a-tabs>
        </CCard>

        <PmBaseInfo type='myPm' userDDId={loginUserInfo.value.userId}></PmBaseInfo>
      </div>
    )
  }
})
